module(...,package.seeall)

require "getApn"

--是否首次上电（避免 IP_READY_IND 消息重复）
local bootOnce = true
--飞控升级检查
--local fcUdpChkOnce = true



--用于设置imei，避免重复获取成空值的情况
sys.subscribe("IMEI_READY_IND", function() 
	if nvm.get("modIMEI")=="" or nvm.get("modIMEI")==nil then
		nvm.set("modIMEI", misc.getImei())
	end
end)
--用于设置imsi/iccid，避免重复获取成空值的情况
sys.subscribe("IMSI_READY", function() 
	if nvm.get("simIMSI")=="" or nvm.get("simIMSI")==nil or nvm.get("simIMSI")=="000000000000000" then
		nvm.set("simIMSI", sim.getImsi())
	end
	
	if nvm.get("simICCID")=="" or nvm.get("simICCID")==nil or nvm.get("simICCID")=="00000000000000000000" then
		nvm.set("simICCID", sim.getIccid())
	end
end)



--记录当前架次上电时间
sys.subscribe("NTP_SUCCEED", function()
	nvm.set("lstBootTime", nvm.get("bootTime")) 
	nvm.set("bootTime", os.time())
end)



--网络就绪
--优先开始202升级。升级的回调函数中，处理检查飞控的逻辑
sys.subscribe("IP_READY_IND", function()
	if bootOnce==true then
		local curTime = os.time()
		--http://t.jiyiuav.com:8118/4g/iot/upgrade?sn=866262049349474&ti=1587085487&es=55a792&vs=1
		local updateURL = 	nvm.get("apiSvr").."/4g/iot/upgrade?sn="..nvm.get("modIMEI").."&ti="..curTime
							.."&es="..crypto.calcHash(curTime).."&vs=".._G.VERSION
		log.info("gsm.chkupd.url", updateURL)
		table.insert(mainFrame.httpReq, {Opera="gsmUpdChk", Url=updateURL, Method="GET", downFile=nil, maxTry=10})
		
		bootOnce = false
	end
end)



--检查飞控升级
sys.subscribe("FC_UPD_CHK", function()
	--if fcUdpChkOnce==true then
		local curTime = os.time()
		--http://t.jiyiuav.com:8118/4g/fc/upgrade?sn=866262049349474&ti=1587085706&es=05c71d&be=0&md5=
		local chkURL = 	nvm.get("apiSvr").."/4g/fc/upgrade?sn="..nvm.get("modIMEI").."&ti="..curTime
						.."&es="..crypto.calcHash(curTime).."&be=0&md5="
		log.info("fc.chkupd.url", chkURL)
		table.insert(mainFrame.httpReq, {Opera="fcUpdChk", Url=chkURL, Method="GET", downFile=nil, maxTry=10})
		--fcUdpChkOnce = false
	--end
end)



--切换sim卡
local simLevel = tonumber(nvm.get("simSelectIndex"))
local switchSimSlot
if string.find(rtos.get_version(), "ASR1802S")~=nil then
	--for 720s
	switchSimSlot = pins.setup(pio.P0_17, simLevel)
else
	--for 720h
	switchSimSlot = pins.setup(pio.P2_4, simLevel)
end
switchSimSlot(simLevel)

sys.taskInit(function()
	while not socket.isReady() do
		if rtos.tick()>180*200 then
			simLevel = simLevel==0 and 1 or 0
			nvm.set("simSelectIndex", simLevel)
			log.info("sim", "no sim, restart to switch")
			sys.wait(5000)
			sys.restart("no sim, restart to switch")
		end

		log.info("sim", "no network, checking", rtos.tick()/200)
		sys.wait(1000)
	end
end)



--设置apn
sys.subscribe("IMSI_READY", function()
	local apnTable = getApn.getApnT(sim.getImsi())
	if #apnTable~=0 then
		link.setAPN(unpack(apnTable))
		log.info("apn", "setapn", unpack(apnTable))
	else
		link.setAPN("CMIOT", "", "")
		log.info("apn", "setapn to default: cmiot")
	end
end)

